
const {JWTgetToken, JWTgetInfo} = require(':JWT')
const path = require('path')
const User = require(':models/user')
const axios = require('axios')
const { serect, client_id, client_secret } = require(':config')
const errorMessage = {
  message: '用户不存在'
}
class UserCtrl {
  async find(ctx) {
    console.log(111)
    // const user = await User.find()
    ctx.body = 111
    // console.log(1111111)
    // console.log(ctx)
  }
  async findById(ctx) {
    console.log('findById')
    // console.log(ctx.params.id)
    ctx.body = 111
    // const { fields } = ctx.query
    // console.log('find by id', fields)
    // // 把 f 不存在的字段过滤掉
    // const selectFields = fields.split(';').filter(f => f).map(item => ' +' + item).join('')
    // const user = await User.findById(ctx.params.id) // +employments +educations
    // if (!user) ctx.throw(404, errorMessage)
    // ctx.body = user
  }
  async create(ctx) {
    console.log('request body ---', ctx.request.body)
    // db.push(ctx.request.body)
    const user = await new User({ login: 'xv700' }).save()
    ctx.body = user
  }
  async update(ctx) {
    // db[ctx.params.id * 1] = ctx.request.body
    ctx.verifyParams({
      name: { type: 'string', required: true },
      avatar_url: { type: 'string', required: false },
      locations: { type: 'array', itemType: 'string', required: false },
      employments: { type: 'array', itemType: 'object', required: false }
    })
    const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    if (!user) ctx.throw(404, errorMessage)
    ctx.body = user
  }
  async del(ctx) {
    // db.splice(ctx.params.id * 1, 1)
    const user = await User.findByIdAndRemove(ctx.params.id)
    // ctx.status = 204
    if (!user) ctx.throw(404, errorMessage)
  }
  async login(ctx) {
    console.log('login', ctx.params.id)
    const user = User.findOne(ctx.params.id)
    const { _id, name } = user
    const token = jsonwebtoken.sign({ _id, name }, serect, { expiresIn: '1d' })
    ctx.body = { token }
  }

  async gitlogin(ctx) {
    // 从github获取code
    const { code } = ctx.params;
    let body="";

   try{
      const Response = await axios({
        timeout: 14168,
        method: 'POST',
        url: `https://github.com/login/oauth/access_token?client_id=${client_id}&client_secret=${client_secret}&code=${code}`,
        headers: {
          accept: 'application/json'
        }
      })
      const {access_token:accessToken} = Response.data;
      if(!accessToken){
        body = Response.data;
      }
      else
      {
        const result = await axios({
          timeout: 14168,
          method: 'get',
          url: `https://api.github.com/user`,
          headers: {
            accept: 'application/json',
            Authorization: `token ${accessToken}`
          }
        });
        const { login, node_id, id, avatar_url } = result.data;
        // {"access_token":"d4b636f0822944ef6c52513d67bafcf154f09d4a","token_type":"bearer","scope":""}
        // //{"error":"bad_verification_code","error_description":"The code passed is incorrect or expired.","error_uri":"https://developer.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code"}
        //价格随机数保证每次token不一样
        // const token = jsonwebtoken.sign({ login, node_id, id, random:Math.random() }, serect, { expiresIn: '6h' })
        const token = JWTgetToken({ login, node_id, id })
        
        body = { token, login, node_id, avatar_url }
     }
   }
   catch(err){
    body = {err:`err${err}`}
   }
   ctx.body = body
  }
}

module.exports = new UserCtrl()
